package com.sywb.chuangyebao.view.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sywb.chuangyebao.R;

import org.bining.footstone.log.Logger;
import org.bining.footstone.utils.ToastUtils;
import org.bining.footstone.widget.ProgressWebView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by pxb on 2018/6/20.
 */

public class WebProjectFragment extends BaseStatisticsFragment {
    protected RelativeLayout actionbar;
    private ImageView actionbarBack;
    private ImageView actionbarTips;
    private TextView actionbarTitle;
    private LinearLayout actionbarMenu;
    private View actionbarBottomLine;
    private ProgressWebView commonWebview;
    private int type;
    private String loadUrl;
    private int index;

    /**
     * Fragment 实例
     */
    public static WebProjectFragment newInstance(Object... pramars) {
        WebProjectFragment fragment = new WebProjectFragment();
        fragment.setArguments(getBundle(pramars));
        return fragment;
    }

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.layout_malll;
    }
    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt("p0", type);
        outState.putString("p1", loadUrl);
        outState.putInt("p3",index);
        super.onSaveInstanceState(outState);
    }
    @SuppressLint("AddJavascriptInterface")
    @Override
    public void initView(View view, Bundle bundle) {
        super.initView(view, bundle);
        if (bundle == null) {
            type = getArguments().getInt("p0", 0);
            loadUrl = getArguments().getString("p1", "");
            index = getArguments().getInt("p3");
        } else {
            type = bundle.getInt("p0", 0);
            loadUrl = bundle.getString("p1", "");
        }

        actionbar = (RelativeLayout) getView(R.id.actionbar);
        actionbarBack = (ImageView) getView(R.id.actionbar_back);
        actionbarTitle = (TextView) getView(R.id.actionbar_title);
        actionbarMenu = (LinearLayout) getView(R.id.actionbar_menu);
        actionbarBottomLine = (View) getView(R.id.actionbar_bottom_line);
        commonWebview = (ProgressWebView) getView(R.id.common_webview);
        synCookies(mActivity,"");
        initWebView();
        actionbar.setVisibility(View.GONE);
        actionbarBack.setVisibility(View.GONE);
        switch (type){
            case 1:
                setHtml(loadUrl);
                break;
        }
    }

    /**
     * 设置需展示的Html片段
     */
    private void setHtml(String protocol) {
        if (protocol != null) {
            commonWebview.getSettings().setDefaultTextEncodingName("utf-8");
            commonWebview.loadDataWithBaseURL("http://www.3158.cn", protocol, "text/html", "UTF-8", null);
        } else {
            ToastUtils.show(mActivity, "未获取到内容，请稍后重试");
        }

    }

    /**
     * 初始化WebView
     */
    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {

        /**
         * setAllowFileAccess 启用或禁止WebView访问文件数据 setBlockNetworkImage 是否显示网络图像
         * setBuiltInZoomControls 设置是否支持缩放 setCacheMode 设置缓冲的模式
         * setDefaultFontSize 设置默认的字体大小 setDefaultTextEncodingName 设置在解码时使用的默认编码
         * setFixedFontFamily 设置固定使用的字体 setJavaSciptEnabled 设置是否支持Javascript
         * setLayoutAlgorithm 设置布局方式 setLightTouchEnabled 设置用鼠标激活被选项
         * setSupportZoom 设置是否支持变焦
         * */
        WebSettings settings = commonWebview.getSettings();
        settings.setJavaScriptEnabled(true);// 设置支持javascript脚本
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        // 1.NARROW_COLUMNS：可能的话使所有列的宽度不超过屏幕宽度；2.NORMAL：正常显示不做任何渲染；3.SINGLE_COLUMN：把所有内容放大webview等宽的一列中
        // settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);// 排版适应屏幕
        settings.setDisplayZoomControls(false);
        settings.setAllowFileAccess(true); // 启用或禁止WebView访问文件数据
        settings.setBuiltInZoomControls(false); //  隐藏缩放按钮
        settings.setSupportZoom(true); // 支持缩放
        // settings.setUseWideViewPort(true);// 可任意比例缩放
        settings.setLoadWithOverviewMode(true);//setUseWideViewPort方法设置webview推荐使用的窗口；设置webview加载的页面的模式
        settings.setGeolocationEnabled(true);// 启用地理定位
        settings.setDomStorageEnabled(true);
        settings.setSaveFormData(true);// 保存表单数据
        // settings.setSavePassword(true);
        // settings.setTextZoom(200);
        // settings.setMixedContentMode(1);
//         settings.setAcceptThirdPartyCookies();
        settings.setAllowFileAccess(true);
        settings.setAllowContentAccess(true);
        settings.setAllowFileAccessFromFileURLs(true);
        settings.setAllowUniversalAccessFromFileURLs(true);

        commonWebview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String webTitle) {
                super.onReceivedTitle(view, webTitle);
            }
        });

        commonWebview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return false;
            }
        });
    }


    /**
     * 同步一下cookie
     * context：上下文
     * url要访问的url
     */
    public void synCookies(Context context, String cookie) {
        try {
            // String url = HttpUtils.getHttpUrl() + Constants.POST_GET_CODE + "?version=" + ApkUtils.getVersionName();
            String url = "http://www.3158.cn";

            CookieSyncManager.createInstance(context);
            CookieManager cookieManager = CookieManager.getInstance();

            String cook = cookieManager.getCookie(url);
            System.out.println("getCookie:  -----------" + cook);

            // CookieManager.setAcceptFileSchemeCookies(true);
            // cookieManager.acceptCookie();
            // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // cookieManager.acceptThirdPartyCookies(webContent);
            // }

            cookieManager.setAcceptCookie(true);
            cookieManager.removeSessionCookie();// 移除
            // cookieManager.removeAllCookie();

            cookieManager.setCookie(url, "_J_SITE=" + cookie + "-android");

            CookieSyncManager.getInstance().sync();

            cook = cookieManager.getCookie(url);
            System.out.println("getCookie:  -----------" + cook);
        } catch (Exception e) {
        }
    }
}
